import axios from 'axios'
import Vue from 'vue'
import store from '@/store'
import router from '@/router'
import { Message, Loading } from 'element-ui'

const baseURL = `${process.env.VUE_APP_API_BASE_URL}/`
const pending = []
const MyCancelToken = axios.CancelToken
const cancelPending = (config) => {
  pending.forEach((item, index) => {
    if (!!config) {
      if (item.u == config.url) {
        item.f() // 取消请求
        pending.splice(index, 1) // 移除当前请求记录
      }
    } else {
      item.f() // 取消请求
      pending.splice(index, 1) // 移除当前请求记录
    }
  })
}
// 封装加载动画
let loading
function startLoading () {
  loading = Loading.service({
    lock: true,
    text: '加载中......',
    background: 'rgba(0, 0, 0, 0)'
  })
}
function endLoading() {
  loading.close()
}

class HttpRequest {
  constructor (baseUrl = baseURL) {
    this.baseUrl = baseUrl
    this.queue = {}
  }

  getInsideConfig () {
    const config = {
      baseURL: this.baseUrl
    }
    return config
  }

  distroy (url) {
    delete this.queue[url]
    if (!Object.keys(this.queue).length) {
      // Spin.hide()
    }
  }

  // 拦截器
  interceptors (instance, url) {
    instance.interceptors.request.use(config => {
      if (config.headers.loading !== false) {
        startLoading()
      }
      // 添加全局的loading
      // Spin.show()
      if (!Object.keys(this.queue).length) {
        // Spin.show()
      };
      this.queue[url] = true
      // const { user } = store.getters.storages
      // const { info } = user
      // const { bigToken } = info
      // let authData = {}
      // if (bigToken) {
      //   authData = {
      //     accessToken: bigToken,
      //     accountId: info.id,
      //     accountType: 4,
      //     userRoles: info.userRoles
      //   }
      // }
      config.data = {
        ...config.data,
        // ...authData,
        traceId: +new Date()
      }
      cancelPending(config)
      config.cancelToken = new MyCancelToken((c) => {
        pending.push({ u: config.url, f: c })
      })
      return config
    }, error => {
      if (config && config.code === 302) {
        Message.error('登录失效')
        store.dispatch('toLogin')
      }
      return Promise.reject(error)
    })
    instance.interceptors.response.use(res => {
      if (loading) {
        endLoading()
      }
      // console.log(res)
      // 状态码拦截
      if (res.data.code === 302) {
        Message.error('登录失效')
        store.dispatch('toLogin')
      } else if (res.data.code !== '0' && res.data.res !== '1' && res.data.retCode !== '0000') {
        Message.error(`${res.data.msg}`)
      }
      this.distroy(url)
      const { data } = res
      return data
    }, error => {
      console.log(error)
      if (loading) {
        console.log(error.response)
        endLoading()
      }
      if (error.response) {
        if(error.response.data.msg) {
          Message.error(error.response.data.msg)
        }
      }
      this.distroy(url)
      return Promise.reject(error.response && error.response.data ? error.response.data : '请求服务失败')
    })
  }

  request (options) {
    const instance = axios.create()
    options = Object.assign(this.getInsideConfig(), options)
    this.interceptors(instance, options.url)
    return instance(options)
  }
}
export default HttpRequest
